package com.headhunter.portlet;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.headhunter.portlet.dao.VocationDAO;
import com.headhunter.portlet.domain.Vocation;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/test/resources/data-test.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class VocationDAOTestCase {
	@Autowired
	private VocationDAO vocationDAO;
	@Autowired
	private DriverManagerDataSource dataSource;
	private JdbcTemplate jdbcTemplate;

	@PostConstruct
	public void init() {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	@Before
	public void executeQuery() {
		jdbcTemplate.execute("insert into VOCATIONS (COMPANY_ID, VOCATION_NAME, " +
				"SALARY, EXPERIENCE, START_DATE, EXPIRATION_DATE, DESCRIPTION) " +
				"values (10, 'vocation', '123', '1 year', '12.12.2010', " +
				"'12.12.2011','desc of vocation')");
	}

	@Test
	public void notNull() {
		Assert.assertNotNull("Error connection to DB",
				vocationDAO.getVocationsListOrderByDate());
	}

	@Test
	public void testVocationsListOrderByDate() {
		List query = jdbcTemplate
				.queryForList("select * from vocations order by start_date desc");	
		Assert.assertEquals("Wrong list of vocations", query.toString(),
				vocationDAO.getVocationsListOrderByDate().toString());
	}

	@Test
	public void testAddVocation() {
		Vocation v = new Vocation();
		v.setCompanyId(666l);
		v.setDescription("Desc 666");
		v.setExpDate(new Date());
		v.setExperience("666 years");
		v.setSalary("666.666");
		v.setStartDate(new Date(110, 9, 10));
		v.setVocationName("Vocation numb 666");

		vocationDAO.addVocation(v);
		
		String testQuery = "select * from vocations where COMPANY_ID=666 AND " +
				"VOCATION_NAME='Vocation numb 666' AND " +
				"SALARY='666.666' AND EXPERIENCE='666 years' AND " +
				"START_DATE='2010-10-10 00:00:00' AND EXPIRATION_DATE=NOW() " +
                "AND DESCRIPTION='Desc 666'";
		Assert.assertTrue("Vocation wasn't added", 
				!jdbcTemplate.queryForList(testQuery).isEmpty());
	}
}
